<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>车型配置模板列表</title>
  <!-- 引入 Element UI 的样式 -->
  <!-- <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" /> -->
  <link rel="stylesheet" href="../../assets/css/element-ui.css" />
  <link rel="stylesheet" href="../../assets/css/styles.css" />
  <script src="../../assets/js/cdn.js"></script>
  <link rel="stylesheet" href="../../assets/fontawesome-free-6.7.2-web/css/all.min.css" />
</head>
<body>
<div id="app">
  <lx-header slot="header" v-on:toggle="isToggle = !isToggle" :type="2"></lx-header>
  <div class="main-content">
    <div class="content" style="width: 100%">

      <!--          <el-row :gutter="10" class="mb8">-->
      <!--                <el-col :span="1.5">-->
      <!--                    <el-button type="primary" plain size="mini" @click="handleAdd">新增</el-button>-->
      <!--                </el-col>-->
      <!--            </el-row>-->

      <div class="center-grid mb-20">
        <el-table v-loading="loading" :data="tableData" :span-method="objectSpanMethod" border>
          <el-table-column v-for="(item, index) in tableColumnData" :key="index" :label="item.fieldName" min-width="150" :width="item.width">
            <template slot-scope="scope">
              <template v-if="item.fieldApi === 'carPlatformName'"> {{ scope.row.carPlatformCode }}-{{ scope.row[item.fieldApi] }} </template>
              <template v-else-if="item.fieldApi === 'carModelName'"> {{ scope.row.carModelCode }}-{{ scope.row[item.fieldApi] }} </template>
              <template v-else> {{ scope.row[item.fieldApi] }} </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" :show-overflow-tooltip="false" width="210" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text"  @click="detailView(scope.row)">详情</el-button>
              <!--                        <el-button size="mini" type="text"  @click="handleUpdate(scope.row)">修改</el-button>-->
              <el-button size="mini" type="text"  @click="processesSetting(scope.row)">配置</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            v-show="total>0"
            :total="total"
            :current-page.sync="queryParams.pageNum"
            :page-size.sync="queryParams.pageSize"
            @current-change="getList"
        />
      </div>
    </div>
  </div>

  <!-- 添加或修改对话框 -->
  <el-dialog :title="title" :visible.sync="open" :fullscreen="true" width="800px" append-to-body>
    <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="模板名称" prop="ptName">
        <el-input v-model="form.ptName" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="车平台" prop="carPlatformCode">
        <el-select v-model="form.carPlatformCode" placeholder="请选择车平台" :disabled="submitFlag === 1" @change="getCarModelList()">
          <el-option v-for="item in carPlatformOptions" :key="item.carPlatformCode" :label="item.carPlatformCode+'-'+item.carPlatformName" :value="item.carPlatformCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="车型号" prop="carModelCode">
        <el-select v-model="form.carModelCode" placeholder="请选择车型号" :disabled="submitFlag === 1">
          <el-option v-for="item in carModelOptions" :key="item.carModelCode" :label="item.carModelCode+'-'+item.carModelName" :value="item.carModelCode" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>

  <el-dialog title="配置" :visible.sync="settingOpen" :fullscreen="true" width="800px" append-to-body>
    <div style="display: inline-flex;width: 100%;">
      <div style="width: 40%;margin-left: 5%">
        <h2>可选配置</h2>
        <el-table ref="optionsObjTable" v-loading="loading" :data="optionsObj" :height="450">
          <el-table-column label="大类名称" prop="bigConfigName">
            <template slot-scope="scope">
              <template> {{ scope.row.bigConfigCode+'-'+scope.row.bigConfigName }} </template>
            </template>
          </el-table-column>
          <el-table-column label="小类名称" prop="smallConfigName" min-width="150">
            <template slot-scope="scope">
              <template> {{ scope.row["smallConfigCode"]+'-'+scope.row["smallConfigName"] }} </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" :show-overflow-tooltip="false" width="220" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text"  @click="saveSetting(scope.row,index)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="width: 40%;margin-left: 10%">
        <h2>已选配置</h2>
        <el-table ref="carModelSmallConfigsTable" v-loading="loading"
                  :data="carModelSmallConfigs"
                  class="dragging-table"
                  :height="450">
          <el-table-column label="大类名称" prop="bigConfigName">
            <template slot-scope="scope">
              <template> {{ scope.row.bigConfigCode+'-'+scope.row.bigConfigName }} </template>
            </template>
          </el-table-column>
          <el-table-column label="小类名称" prop="smallConfigName" min-width="150">
            <template slot-scope="scope">
              <template> {{ scope.row["smallConfigCode"]+'-'+scope.row["smallConfigName"] }} </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" :show-overflow-tooltip="false" width="220" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text"  @click="moveToTop(scope.row,scope.$index)">上移</el-button>
              <el-button size="mini" type="text"  @click="moveToBottom(scope.row,scope.$index)">下移</el-button>
              <el-button size="mini" type="text"  @click="delSetting(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <!--<el-table-column label="排序" prop="sort">
              <template slot-scope="scope">
                  <template> {{ scope.row["sort"] }} </template>
              </template>
          </el-table-column>-->
        </el-table>

      </div>
    </div>
  </el-dialog>

</div>
<script src="../../assets/js/constant.js"></script>
<script src="../../assets/js/utils.js"></script>
<script src="../../assets/js/auth.js"></script>
<script src="../../assets/js/axios.min.js"></script>
<script src="../../assets/js/Sortable.min.js"></script>
<!-- 引入 Vue.js -->
<script src="../../assets/js/vue.js"></script>
<script src="../../assets/js/element-ui.js"></script>
<script type="module">
    import LxHeader from '../../pages/components/LxHeader/index.js'
    Vue.component('lx-header', LxHeader)
    checkAuthentication(2)
    new Vue({
        el: '#app',
        components: {},
        data() {
            return {
                currentUser: JSON.parse(localStorage.getItem('currentUser')) || {},
                userMenuList: JSON.parse(localStorage.getItem('userMenuList')) || [],
                businessCenters: [
                    { name: '订单中心', path: '../index.html' },
                    { name: '用户中心', path: '#' },
                    { name: '产品中心', path: '#' },
                    { name: '库存中心', path: '#' },
                    { name: '财务中心', path: '#' },
                    { name: '数据中心', path: '#' },
                    { name: '系统中心', path: '#' },
                    { name: '消息中心', path: '#' }
                ],
                queryParams: {
                    pageNo: 1,
                    pageSize: 10,
                    carModelCode: '',
                    carModelName: ''
                },
                total: 0,
                tableData: [],
                tableColumnData: [
                    {
                        fieldName: '车平台',
                        fieldApi: 'carPlatformName'
                    },
                    {
                        fieldName: '车型号',
                        fieldApi: 'carModelName'
                    }
                ],
                // 遮罩层
                loading: true,
                allOptionsObj: [],
                optionsObj: [],
                selectedSmallConfigCodes:[],
                carModelSmallConfigs:[],
                carPlatformOptions:[],
                carModelOptions:[],
                // 选中数组
                carModelCodes: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                settingOpen: false,
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                    carModelCode: [{ required: true, message: '请选择车型号', trigger: 'blur' }],
                },
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                submitFlag: 0,
                request_host: request_host,
                pageSizes: pageSizes,
                multipleSelection: []
            }
        },
        created() {
            this.getOptions()
            // this.getCarPlatformList()
            this.init()
        },
        methods: {
            exit,
            init() {
                this.getList()
            },
            getList() {
                this.loading = true
                try {
                    axios.get(`${this.request_host}/system/model/list`,{ params: this.queryParams }).then((response) => {
                        if (response.status == 200) {
                            this.tableData = response.data.rows
                            this.total = response.data.total
                            this.loading = false
                            this.calculateSpanArr()
                        }
                    })
                } catch (error) {
                    console.error('请求失败:', error)
                }
            },
            getOptions() {
                axios.get(`${this.request_host}/system/smallConfig/allList`).then((response) => {
                    if (response.status == 200) {
                        this.allOptionsObj = response.data.data
                        this.optionsObj = response.data.data
                        /*response.data.data.forEach(element => {
                            this.optionsObj.push({"key":element.carModelCode,"label":element.carModelCode+"-"+element.smallConfigName})
                        });*/
                    }
                })
            },
            getCarPlatformList() {
                axios.get(`${this.request_host}/system/platform/allList`).then((response) => {
                    if (response.status == 200) {
                        response.data.data.forEach(element => {
                            this.carPlatformOptions.push(element)
                        });
                    }
                })
            },
            getCarModelList() {
                console.log(this.form)
                this.carModelOptions = []
                axios.get(`${this.request_host}/system/model/allList?carPlatformCode=${this.form.carPlatformCode}`).then((response) => {
                    if (response.status == 200) {
                        response.data.data.forEach(element => {
                            var item = {"carModelCode": element.carModelCode,"carModelName":element.carModelName}
                            this.carModelOptions.push(item)
                        });
                    }
                })
            },
            /** 提交按钮 */
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        this.form.carModelSmallConfigs = this.carModelSmallConfigs
                        if (this.submitFlag == 0){
                            this.form.carModelCode = this.form.carModelCode;
                            const carModelCode = this.form.carModelCode
                            // 新增
                            axios.post(`${this.request_host}/system/pt`, this.form)
                                .then(response => {
                                    if (response.data.code == 200){
                                        this.$message.success("提交成功")
                                        this.cancel();
                                        this.getList()
                                        const params = `carModelCode=`+carModelCode;
                                        const url = `pt_item.html?${params}`;
                                        window.open(url, '_blank');
                                    }else {
                                        this.$message.error(response.data.msg)
                                    }

                                })
                        }else{
                            this.form.carModelCode = this.form.carModelCode;
                            const carModelCode = this.form.carModelCode
                            //修改提交
                            axios.put(`${this.request_host}/system/pt`, this.form)
                                .then(response => {
                                    if (response.data.code == 200){
                                        this.$message.success("提交成功")
                                        this.cancel();
                                        this.getList();
                                        const params = `carModelCode=`+carModelCode;
                                        const url = `pt_item.html?${params}`;
                                        window.open(url, '_blank');
                                    }else {
                                        this.$message.error(response.data.msg)
                                    }

                                })
                        }

                    }
                })
            },
            /** 保存配置配制小类 */
            saveSetting(row) {
                this.selectedSmallConfigCodes.push(row.smallConfigCode)
                this.carModelSmallConfigs.push({"smallConfigCode":row.smallConfigCode,"smallConfigName":row.smallConfigName,"sort":this.carModelSmallConfigs.length+1})
                this.optionsObj = this.optionsObj.filter(item => item.smallConfigCode !== row.smallConfigCode);
                this.form.carModelSmallConfigs = this.carModelSmallConfigs
                this.form.carModelCode = this.form.carModelCode.toUpperCase();
                // 新增
                axios.post(`${this.request_host}/system/carModelSmallConfig/saveSetting`, this.form)
                    .then(response => {
                        if (response.data.code === 200){
                            //window.location.reload()
                        }else {
                            this.$message.error(response.data.msg)
                        }

                    })
            },
            delSetting(row) {
                this.carModelSmallConfigs = this.carModelSmallConfigs.filter(item => item.smallConfigCode !== row.smallConfigCode);
                this.selectedSmallConfigCodes = this.selectedSmallConfigCodes.filter(item => item!== row.smallConfigCode);
                this.optionsObj = this.allOptionsObj.filter(item =>!this.selectedSmallConfigCodes.includes(item.smallConfigCode));
                this.form.carModelSmallConfigs = this.carModelSmallConfigs
                this.form.carModelCode = this.form.carModelCode.toUpperCase();
                // 新增
                axios.post(`${this.request_host}/system/carModelSmallConfig/saveSetting`, this.form)
                    .then(response => {
                        if (response.data.code === 200){
                            //window.location.reload()
                        }else {
                            this.$message.error(response.data.msg)
                        }

                    })
            },
            // 取消按钮
            cancel() {
                this.open = false
                this.settingOpen = false
                this.form = {}
            },
            handleQuery() {
                this.getList()
            },
            resetQuery() {
                this.queryParams = {
                    pageNo: 1,
                    pageSize: 10,
                    carModelCode: '',
                    carModelName: ''
                }
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.resetQuery()
                this.selectedSmallConfigCodes = []
                this.carModelSmallConfigs = []
                this.open = true
                this.form = {}
                this.submitFlag = 0
                this.title = "添加车型配置模板"
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.resetQuery()
                const carModelCode = row.carModelCode || this.carModelCodes[0]
                // 这里替换为实际的API调用
                axios.get(`${this.request_host}/system/pt/` + carModelCode)
                    .then(response => {
                        this.form = response.data.data
                        this.carModelSmallConfigs = this.form.carModelSmallConfigs || []
                        this.carModelSmallConfigs.forEach(item=>{
                            this.selectedSmallConfigCodes.push(item.carModelCode)
                        })
                        this.open = true
                        this.title = "修改车型配置模板"
                        this.getCarModelList()
                    });
                this.submitFlag = 1
            },
            /** 修改按钮操作 */
            processesSetting(row) {
                this.resetQuery()
                // this.getCarModelList()
                const carModelCode = row.carModelCode || this.carModelCodes[0]
                this.form.carModelCode = carModelCode
                // 这里替换为实际的API调用
                axios.get(`${this.request_host}/system/carModelSmallConfig/` + carModelCode)
                    .then(response => {
                        this.selectedSmallConfigCodes = []
                        this.form.carModelSmallConfigs = response.data.data
                        if(this.form.carModelSmallConfigs){
                            this.carModelSmallConfigs = this.form.carModelSmallConfigs
                            this.carModelSmallConfigs.forEach(item=>{
                                this.selectedSmallConfigCodes.push(item.smallConfigCode)
                            })
                        }else{
                            this.carModelSmallConfigs = []
                        }
                        this.optionsObj = this.allOptionsObj.filter(item => !this.selectedSmallConfigCodes.includes(item.smallConfigCode));
                        this.settingOpen = true
                        this.title = "修改车型配置模板"
                    }).then(()=>{
                    const tableBody = document.querySelector('.dragging-table .el-table__body-wrapper tbody');
                    Sortable.create(tableBody, {
                        handle: '.el-table__row', // 使每行可拖动
                        onEnd: this.handleDragEnd // 拖动结束时处理排序
                    });
                });
            },
            handleDragEnd(evt) {
                const oldIndex = evt.oldIndex;
                const newIndex = evt.newIndex;
                //往后挪
                const arr = []
                if(oldIndex<newIndex){
                    for(let i=0;i<this.carModelSmallConfigs.length;i++){
                        if(i<oldIndex || i>newIndex){
                            arr.push(this.carModelSmallConfigs[i])
                        }else if(i>=oldIndex && i<newIndex){
                            arr.push(this.carModelSmallConfigs[i+1])
                        }else if(i===newIndex){
                            arr.push(this.carModelSmallConfigs[oldIndex])
                        }
                    }
                }else {
                    for(let i=0;i<this.carModelSmallConfigs.length;i++){
                        if(i<newIndex || i>oldIndex){
                            arr.push(this.carModelSmallConfigs[i])
                        }else if(i>newIndex && i<=oldIndex){
                            arr.push(this.carModelSmallConfigs[i-1])
                        }else if(i===newIndex){
                            arr.push(this.carModelSmallConfigs[oldIndex])
                        }
                    }
                }
                this.carModelSmallConfigs = arr
                this.form.carModelSmallConfigs = this.carModelSmallConfigs
                this.form.carModelCode = this.form.carModelCode.toUpperCase();
                // 新增
                axios.post(`${this.request_host}/system/carModelSmallConfig/saveSetting`, this.form)
                    .then(response => {
                        if (response.data.code === 200){
                            //window.location.reload()
                        }else{
                            this.$message.error(response.data.msg)
                        }
                    })
            },
            moveToTop(row,index) {
                if(index!==0){
                    this.carModelSmallConfigs.splice(index-1,0,this.carModelSmallConfigs.splice(index,1)[0])
                }
                this.form.carModelSmallConfigs = this.carModelSmallConfigs
                this.form.carModelCode = this.form.carModelCode.toUpperCase();
                // 新增
                axios.post(`${this.request_host}/system/carModelSmallConfig/saveSetting`, this.form)
                    .then(response => {
                        if (response.data.code === 200){
                            //window.location.reload()
                        }else{
                            this.$message.error(response.data.msg)
                        }
                    })
            },
            moveToBottom(row,index) {
                if(index!==this.carModelSmallConfigs.length-1){
                    this.carModelSmallConfigs.splice(index+1,0,this.carModelSmallConfigs.splice(index,1)[0])
                }
                this.form.carModelSmallConfigs = this.carModelSmallConfigs
                this.form.carModelCode = this.form.carModelCode.toUpperCase();
                // 新增
                axios.post(`${this.request_host}/system/carModelSmallConfig/saveSetting`, this.form)
                    .then(response => {
                        if (response.data.code === 200){
                            //window.location.reload()
                        }else{
                            this.$message.error(response.data.msg)
                        }
                    })
            },
            // 分页数量切换
            handleSizeChange(val) {
                this.$set(this.queryParams, 'pageSize', val)
                this.getData()
            },
            // 当前页码切换
            handleCurrentChange(val) {
                this.$set(this.queryParams, 'pageNo', val)
                this.getData()
            },
            detailView(row) {
                const carModelCode = row.carModelCode;
                const params = `carModelCode=${encodeURIComponent(carModelCode)}`;
                const url = `car_model_config_template_item.html?${params}`;
                window.open(url, '_blank');
            },
            openMenu(url) {
                window.open(url)
            },
            // 计算合并单元格的数组
            calculateSpanArr() {
                this.spanArr = [];
                let pos = 0;
                for (let i = 0; i < this.tableData.length; i++) {
                    if (i === 0) {
                        this.spanArr.push(1);
                        pos = 0;
                    } else {
                        if (this.tableData[i].carPlatformCode === this.tableData[i - 1].carPlatformCode) {
                            this.spanArr[pos]++;
                            this.spanArr.push(0);
                        } else {
                            this.spanArr.push(1);
                            pos = i;
                        }
                    }
                }
            },
            // 合并单元格的方法
            objectSpanMethod({ row, column, rowIndex, columnIndex }) {
                if (columnIndex === 0) {
                    const _row = this.spanArr[rowIndex];
                    const _col = _row > 0 ? 1 : 0;
                    return {
                        rowspan: _row,
                        colspan: _col
                    };
                }
                return {
                    rowspan: 1,
                    colspan: 1
                };
            }
        }
    })
</script>
<style>
    .el-table th.el-table__cell {
        background-color: #f2f2f2; /* 例如，设置为浅灰色 */
    }
    .mb8 {
        margin-bottom: 10px;
    }
    .el-transfer-panel{
        width: 250px;
        height: 450px;
    }
    .el-transfer-panel__list{
        height: 400px;
    }
</style>
</body>
</html>
